package com.xhx.accounting.ui.dashboard;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xhx.accounting.DBDao;
import com.xhx.accounting.R;
import com.xhx.accounting.databinding.FragmentDashboardBinding;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

public class DashboardFragment extends Fragment {

    private FragmentDashboardBinding binding;
    private PieChart chart;
    private LineChart chart2;
    private View outLine,inLine;
    private View weekSelectBg, monthSelectBg, yearSelectBG;
    private TextView out, in;
    private int displayType;
    private Long startTimeStamp,endTimeStamp;
    private DBDao db;
    private List<Map<String, Object>> mData,mData2;
    private ListView lv;
    private dashboardAdapter mAdapter;
    private List<String> weekDisplay,yearDisplay,monthDisplay;
    private XAxis x;
    private ImageView cgChart;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        lv = root.findViewById(R.id.date_list);
        View emptyView = root.findViewById(R.id.empty);
        lv.setEmptyView(emptyView);

        //mdata初始化
        mData = new ArrayList<>();
        mData2 = new ArrayList<>();
        //
        mAdapter = new dashboardAdapter(getActivity(),mData);
        lv.setAdapter(mAdapter);

        //设置饼图
        chart = root.findViewById(R.id.pieChart);
        initPieChart();
        //设置线图
        chart2 = root.findViewById(R.id.lineChart);
        initLineChart();

        //设置范围选择器
        outLine = root.findViewById(R.id.outline);
        inLine = root.findViewById(R.id.inline);
        out = root.findViewById(R.id.out);
        in = root.findViewById(R.id.in);
        weekSelectBg = root.findViewById(R.id.week_select_box);
        monthSelectBg = root.findViewById(R.id.month_select_box);
        yearSelectBG = root.findViewById(R.id.year_select_box);
        cgChart = root.findViewById(R.id.cgChart);
        out.setOnClickListener(v -> {
            getCost();
        });
        in.setOnClickListener(v -> {
            getIncome();
        });
        weekSelectBg.setOnClickListener(v -> {
            getWeek();
        });
        monthSelectBg.setOnClickListener(v -> {
            getMonth();
        });
        yearSelectBG.setOnClickListener(v -> {
            getYear();
        });
        cgChart.setOnClickListener(v -> {
            if (chart.getVisibility() == View.VISIBLE){
                chart.setVisibility(View.INVISIBLE);
                chart2.setVisibility(View.VISIBLE);
            } else {
                chart2.setVisibility(View.INVISIBLE);
                chart.setVisibility(View.VISIBLE);
            }
        });

        //第一次初始化
        init();

        return root;
    }

    //initPieChart
    private void initPieChart(){
        chart.setTouchEnabled(false);
        chart.setUsePercentValues(true);
        chart.getDescription().setEnabled(false);
        chart.setDragDecelerationFrictionCoef(0.95f);
        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(Color.WHITE);
        chart.setTransparentCircleColor(Color.WHITE);
        chart.setTransparentCircleAlpha(110);
        chart.setHoleRadius(28f);
        chart.setTransparentCircleRadius(31f);
        chart.setDrawCenterText(true);
        chart.setCenterTextSize(20f);
        chart.setEntryLabelTextSize(15f);
        chart.setRotationAngle(-90);
        // enable rotation of the chart by touch
        chart.setRotationEnabled(true);
        chart.setHighlightPerTapEnabled(true);
        chart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);
        Legend l = chart.getLegend();
        l.setEnabled(false);
        chart.setEntryLabelColor(Color.BLACK);
        chart.setEntryLabelTextSize(12f);
        chart.setDrawEntryLabels(true);
    }

    private void initLineChart(){
        //chart2.setBackgroundColor(Color.rgb(255, 255, 255));
        chart2.getDescription().setEnabled(false);
        chart2.setTouchEnabled(false);
        chart2.setDragEnabled(false);
        chart2.setScaleEnabled(true);
        chart2.setPinchZoom(false);
        chart2.setDrawGridBackground(false);
        chart2.setMaxHighlightDistance(300);

        x = chart2.getXAxis();
        x.setEnabled(false);

        YAxis y = chart2.getAxisLeft();
        y.setLabelCount(6, false);
        y.setTextColor(Color.BLACK);
        y.setDrawGridLines(true);
        y.setAxisLineColor(Color.BLACK);
        y.setAxisMinimum(0);
        y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

        chart2.getAxisRight().setEnabled(false);
        chart2.getLegend().setEnabled(false);
        chart2.animateXY(2000, 2000);
    }

    //initData
    private void init(){
        outLine.setVisibility(View.VISIBLE);
        inLine.setVisibility(View.INVISIBLE);
        displayType = -1;
        getWeek();
    }

    private void getWeek(){
        weekSelectBg.setBackground(getActivity().getDrawable(R.drawable.week_selected));
        monthSelectBg.setBackground(getActivity().getDrawable(R.drawable.month_chart));
        yearSelectBG.setBackground(getActivity().getDrawable(R.drawable.year));
        // 获取星期日开始时间戳
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar. DAY_OF_WEEK, Calendar.SUNDAY);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        startTimeStamp = cal.getTimeInMillis()/1000;
        // 获取星期六结束时间戳
        cal = Calendar.getInstance();
        cal.set(Calendar. DAY_OF_WEEK, Calendar.SATURDAY );
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        endTimeStamp = cal.getTimeInMillis()/1000;
        setData(startTimeStamp,endTimeStamp,displayType);

    }
    private void getMonth(){
        weekSelectBg.setBackground(getActivity().getDrawable(R.drawable.week));
        monthSelectBg.setBackground(getActivity().getDrawable(R.drawable.month_chart_selected));
        yearSelectBG.setBackground(getActivity().getDrawable(R.drawable.year));
        //月初
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0); //获取当前月第一天
        cal.set(Calendar.DAY_OF_MONTH, 1); //设置为1号,当前日期既为本月第一天
        cal.set(Calendar.HOUR_OF_DAY, 0); //将小时至0
        cal.set(Calendar.MINUTE, 0); //将分钟至0
        cal.set(Calendar.SECOND,0); //将秒至0
        cal.set(Calendar.MILLISECOND, 0); //将毫秒至0
        startTimeStamp = cal.getTimeInMillis()/1000;
        // 获取星期六结束时间戳
        cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //获取当前月最后一天
        cal.set(Calendar.HOUR_OF_DAY, 23); //将小时至23
        cal.set(Calendar.MINUTE, 59); //将分钟至59
        cal.set(Calendar.SECOND,59); //将秒至59
        cal.set(Calendar.MILLISECOND, 999); //将毫秒至999
        endTimeStamp = cal.getTimeInMillis()/1000;
        setData(startTimeStamp,endTimeStamp,displayType);
    }
    private void getYear(){
        weekSelectBg.setBackground(getActivity().getDrawable(R.drawable.week));
        monthSelectBg.setBackground(getActivity().getDrawable(R.drawable.month_chart));
        yearSelectBG.setBackground(getActivity().getDrawable(R.drawable.year_selected));
        //月初
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, 0);
        cal.add(Calendar.DATE, 0);
        cal.add(Calendar.MONTH, 0); //获取当前月第一天
        cal.set(Calendar.DAY_OF_YEAR, 1); //设置为1号,当前日期既为本月第一天
        cal.set(Calendar.HOUR_OF_DAY, 0); //将小时至0
        cal.set(Calendar.MINUTE, 0); //将分钟至0
        cal.set(Calendar.SECOND,0); //将秒至0
        cal.set(Calendar.MILLISECOND, 0); //将毫秒至0
        startTimeStamp = cal.getTimeInMillis()/1000;
        // 获取星期六结束时间戳
        cal = Calendar.getInstance();// 获取当前日期
        int year = cal.get(Calendar.YEAR);
        cal.clear();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        cal.roll(Calendar.DAY_OF_YEAR, -1);
        endTimeStamp = cal.getTimeInMillis()/1000;
        setData(startTimeStamp,endTimeStamp,displayType);
    }
    private void getCost(){
        outLine.setVisibility(View.VISIBLE);
        inLine.setVisibility(View.INVISIBLE);
        displayType = -1;
        setData(startTimeStamp,endTimeStamp,displayType);
    }
    private void getIncome(){
        outLine.setVisibility(View.INVISIBLE);
        inLine.setVisibility(View.VISIBLE);
        displayType = 1;
        setData(startTimeStamp,endTimeStamp,displayType);
    }

    private void setData(Long startTime, Long endTime, int type) {
        db = new DBDao(getActivity());
        //饼图
        mData.clear();
        mData.addAll(db.getChartData(startTime, endTime,type));
        mAdapter.notifyDataSetChanged();

        ArrayList<PieEntry> entries = new ArrayList<>();

        //遍历mData，做一个chart的数据集：
        for (Map<String,Object> tmp:mData){
            Log.d("mData", tmp.toString());
            entries.add(new PieEntry((float) tmp.get("amount"),tmp.get("classification_name").toString(), null));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Results");

        dataSet.setDrawIcons(false);
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(chart));
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        chart.setData(data);
        // undo all highlights
        chart.highlightValues(null);
        chart.invalidate();

        //线图
        ArrayList<Entry> values = new ArrayList<>();

        //数据库操作
        mData2.clear();
        mData2.addAll(db.getLineChartData(startTime, endTime,type));
        Log.d("mData2",mData2.toString());

        for (Map<String,Object> tmp:mData2){
            values.add(new Entry((int) tmp.get("dayId"), (float) tmp.get("total")));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setCubicIntensity(0.2f);
        set1.setDrawFilled(true);
        set1.setDrawCircles(false);
        set1.setLineWidth(1.8f);
        set1.setCircleRadius(4f);
        set1.setCircleColor(Color.BLACK);
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setColor(Color.rgb(87, 185, 255));
        set1.setDrawFilled(false);
        set1.setDrawHorizontalHighlightIndicator(false);

            // create a data object with the data sets
        LineData data3 = new LineData(set1);
        data3.setValueTextSize(9f);
        data3.setDrawValues(false);

            // set data
        chart2.setData(data3);
        chart2.invalidate();
        //}
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}